/**
 * handle group page logic.
 */
var __groupId = null;

function emptyPortlv(lv) {
	lv.find('.port').each(function(i, l){
		l.remove();
	});
}
function refreshPortView(ports) {
    var lv = $("#lvPorts");
    emptyPortlv(lv);
    
    if (__groupId === null) {
        return;
    }

    if(ports.length < 1) {
    	return;
    }
    
    var li = '';
    ports.forEach(function(port) {
			var leftLabel = '<label data-type="horizontal" style="float: left;"><input name="checkbox-0 " type="checkbox">'+port+'</label>';
			var rightLabel = '<label data-type="horizontal" style="float: right;"><a href="#" id="showPort" class="ui-btn ui-corner-all ui-icon-edit ui-btn-icon-notext">Icononly</a></label>';
            li += '<li class="port" id="'+port+'">' + leftLabel + rightLabel+ '</li>';
            });
    lv.append(li);
    lv.listview("refresh");
}

function refreshGroupView(group) {
	$('#textinput-id').val(group.id);
	$('#textinput-type').val(group.type);
	$('#textinput-name').val(group.name);
	$('#textinput-description').val(group.description);
	$('#textinput-gwId').val(group.gwId);

	refreshPortView(group.ports);
}

function loadGroup(groupId) {
	$.ajax({
		url : ('/loadGroup?groupId=' + groupId),
		type : 'GET',
		dataType : 'json',
		success : function(result) {
			if (result.err) {
				showMsgPopup('load group info failed:' + result.err,
						"#groupMgr");
			} else {
				refreshGroupView(result);
			}
		},
		error : function(_, status, e) {
			showMsgPopup('load group info failed:' + e, "#groupMgr");
		}
	});
}

function deleteGroup(groupId) {
	$.ajax({
		url : ('/_deleteGroup?groupId=' + groupId),
		type : 'POST',
		success : function(result) {
			if (result != 'ok') {
				showMsgPopup('load group info failed:' + result.err,
						"#groupMgr");
			} else {
				location.reload();
			}
		},
		error : function(_, status, e) {
			showMsgPopup('delete group failed:' + e, "#groupMgr");
		}
	});
}

function deletePorts(ids) {
	$.ajax({
		url : ('/_deletePorts?groupId=' + __groupId),
		type : 'POST',
		data : {portIds:ids},
		success : function(result) {
			if (result != 'ok') {
				showMsgPopup('load group info failed:' + result.err,
						"#groupMgr");
			} else {
				location.reload();
			}
		},
		error : function(_, status, e) {
			showMsgPopup('delete group failed:' + e, "#groupMgr");
		}
	});
}

function pageinit() {
	$('#lvGroups').find('.groupId').each(function(i, a) {
		var input = $(a).find("input").first();
		var groupId = input.val();
		$(a).off('click').on('click', function(event) {
			__groupId = groupId;
			$("#groupName").text("Group: " + __groupId);
			loadGroup(__groupId);
			event.preventDefault();
		});
	});

	$('#addGroup').off('click').on('click', function(event) {
		$.mobile.changePage("/editGroup?a=newGroup", {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});

	$('#editGroup').off('click').on('click', function(event) {
		if (__groupId == null) {
			showMsgPopup("Please select a group to edit");
			return;
		}
		
		$.mobile.changePage("/editGroup?groupId=" + __groupId, {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});

	$('#deleteGroup').off('click').on('click', function(event) {
		var id = $("#textinput-id").val();
		if (!id || id.length < 1) {
			showMsgPopup("Please select a group to delete");
			return;
		}
		var xdata = {
			title : 'Confirm delete group',
			hint : "Are you sure?",
			msg : "Delete the group with id:" + id
		};
		showConfirmDlg(xdata, function() {
			deleteGroup(id);
		});
		event.preventDefault();
	});

	$('#addPort').off('click').on('click', function(event) {
		if (__groupId == null) {
			showMsgPopup("Please select a group to add port");
			return;
		}
		
		$.mobile.changePage("/addPort?groupId=" + __groupId, {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});

	$("#selectAllPort").off('click').on('click', function(event) {
		$("#lvPorts").find("li").each(function() {
			var li = $(this);
			var checkBox = li.find("input");
			if (checkBox) {
				checkBox.prop('checked', true);
			}
		});
	});

	$("#deSelectAllPort").off('click').on('click', function(event) {
		$("#lvPorts").find("li").each(function(i, a) {
			var li = $(this);
			var checkBox = li.find("input");
			if (checkBox) {
				checkBox.prop('checked', false);
			}
		});
	});
	
	$('#deletePorts').off('click').on('click', function(event) {
        var ids = [];
        var msgStr='';
        
        $("#lvPorts").find("li").each(function() {
              var li = $(this);
              var checkBox = li.find("input");
              if (checkBox && checkBox.is(':checked')) {
                  var id = checkBox.parent().parent().attr('id');
                  var name = checkBox.parent().text();
                  ids.push(id);
                  msgStr +=  name;
              }
          });
        
        if (ids.length == 0) {
            showMsgPopup("no port to be delete!");
        } else {
            var xdata = {title:'Confirm delete ports',hint:"Are you sure to delete ports:", msg:msgStr};
            showConfirmDlg(xdata, function(){
                deletePorts(ids);
            });
        }
	});
}

$(document).on('pageinit', function() {
	pageinit();
});
